<?php
/**
 * Created by PhpStorm.
 * User: Orange
 * Date: 2018/5/5
 * Time: 16:57
 */

namespace app\index\logic;


use app\common\utils\Constant;
use think\Db;
use think\Exception;

class BacteriaLogic
{
    /**
     * 游客搜索
     * @param $keyword
     * @return array
     */
    public function UserSearchByKeyword($keyword)
    {
        Db::startTrans();
        try {
            $count = model('Bacteria')
                ->where('the_latin_name|chinese_name', 'like', '%' . $keyword . '%')->where(array('is_use' => 1))->count();
            $bacteria = model('Bacteria')
                ->where('the_latin_name|chinese_name', 'like', '%' . $keyword . '%')->where(array('is_use' => 1))->order('id desc')->limit(5)->select();
            if ($count > 5) {
                $count = 5;
            }
            for ($i = 0; $i < $count; $i++) {
                $category = $this->searchCategoryByBacteriaId($bacteria[$i]['id']);
                $bacteria[$i]['category'] = $category;
            }
            Db::commit();
            return array('status' => 1, 'data' => $bacteria);
        } catch (Exception $e) {
            Db::rollback();
//            return array('status' => 0, 'error' => $e->getMessage());
            return array('status' => 0, 'error' => "数据出错");
        }
    }

    /**
     * 会员搜索
     * @param $keyword
     * @param $ip
     * @param $token
     * @return array
     */
    public function MemberSearchByKeyword($keyword, $ip, $token)
    {
        Db::startTrans();
        try {
            $count = model('Bacteria')
                ->where('the_latin_name|chinese_name', 'like', '%' . $keyword . '%')->where(array('is_use' => 1))->count();
            $bacteria = model('Bacteria')
                ->where('the_latin_name|chinese_name', 'like', '%' . $keyword . '%')->order('id desc')->where(array('is_use' => 1))->limit(5)->select();
            if ($count > 5) {
                $count = 5;
            }
            for ($i = 0; $i < $count; $i++) {
                $category = $this->searchCategoryByBacteriaId($bacteria[$i]['id']);
                $bacteria[$i]['category'] = $category;
            }
            $logic = new UserLogic();
            $user = $logic->getUserByToken($token);
            $access_log = array('nickname' => $user['data']['name'], 'search_type' => 0, 'ip' => $ip, 'keyword' => $keyword, 'create_time' => time(), 'member_id' => $user['data']['id']);
            model('AccessLog')->create($access_log);
            Db::commit();
            return array('status' => 1, 'data' => $bacteria);
        } catch (Exception $e) {
            Db::rollback();
            //            return array('status' => 0, 'error' => $e->getMessage());
            return array('status' => 0, 'error' => "数据出错");
        }
    }

    public function sumbitBacteria($id, $token)
    {
        Db::startTrans();
        try {
            $bacteria = model('Bacteria')
                ->where(array('id' => $id, 'is_use' => 1))
                ->find();
            if (!$bacteria) {
                return array('status' => 0, 'error' => "菌种不存在");
            }
            $logic = new UserLogic();
            $user = $logic->getUserByToken($token);
            $where['member_id'] = $user['data']['id'];
            $where['status'] = 0;
            $verify_num = model('VerifyLog')->where($where)->count();
            if ($this->isVerifyMaxNum($verify_num)) {
                if ($bacteria['amount'] + $bacteria['in_review'] < $bacteria['demand']) {
                    $data = array('status' => 0, 'create_time' => time(), 'bacteria_id' => $bacteria['id'], 'member_id' => $user['data']['id'], 'chinese_name' => $bacteria['chinese_name'], 'the_latin_name' => $bacteria['the_latin_name'], 'type' => 1);
                    model('Bacteria')->where(array('id' => $bacteria['id']))->update(array('in_review' => $bacteria['in_review'] + 1));
                    model('VerifyLog')->create($data);
                } else {
                    return array('status' => 0, 'error' => "该菌种已达到需求量");
                }
            } else {
                return array('status' => 0, 'error' => "提交审核数量达到上限");
            }
            //发送通知
            $this->sendMessage($user['data']['name'], $bacteria['chinese_name'], 1);
            Db::commit();
            return array('status' => 1, 'data' => '提交成功');
        } catch (Exception $e) {
            Db::rollback();
            //            return array('status' => 0, 'error' => $e->getMessage());
            return array('status' => 0, 'error' => "数据出错");
        }
    }

    public function getBacteria($id)
    {
        Db::startTrans();
        try {
            $bacteria = model('Bacteria')
                ->where(array('id' => $id))
                ->find();
            $category = $this->searchCategoryByBacteriaId($id);
            $bacteria['category'] = $category;

            Db::commit();
            return array('status' => 1, 'data' => $bacteria);
        } catch (Exception $e) {
            Db::rollback();
            //            return array('status' => 0, 'error' => $e->getMessage());
            return array('status' => 0, 'error' => "数据出错" . $e);
        }
    }

    public function editBacteria($data, $token)
    {
        Db::startTrans();
        try {
            $bacteria = model('Bacteria')
                ->where('chinese_name = :chinese_name OR the_latin_name = :the_latin_name', ['chinese_name' => $data['bacteria_name'], 'the_latin_name' => $data['lading_name']])
                ->where(array('is_use' => 1))
                ->find();
            if ($bacteria) {
                return array('status' => 0, 'error' => "菌种已存在，修改失败");
            }
            $logic = new UserLogic();
            $user = $logic->getUserByToken($token);
            $where['member_id'] = $user['data']['id'];
            $where['status'] = 0;
            $verify_num = model('VerifyLog')->where($where)->count();
            if ($this->isVerifyMaxNum($verify_num)) {
                $bacteriaData = array('chinese_name' => $data['bacteria_name'], 'the_latin_name' => $data['lading_name'], 'is_use' => 0);
                $newBacteria = model('Bacteria')->create($bacteriaData);
                $info = array('status' => 0, 'create_time' => time(), 'bacteria_id' => $newBacteria['id'], 'member_id' => $user['data']['id'], 'chinese_name' => $newBacteria['chinese_name'], 'the_latin_name' => $newBacteria['the_latin_name'], 'type' => 0);
                model('VerifyLog')->create($info);
                $row['bacteria_id'] = $newBacteria['id'];
                for ($level = 0; $level <= 6; $level++) {
                    $row['category_id'] = $data['category'][$level];
                    $row['category_name'] = $this->getCategoryChineseName($data['category'][$level]);
                    $row['english_name'] = $this->getCategoryEnglishName($data['category'][$level]);
                    $row['level'] = $level;
                    model('BacteriaCategory')->create($row);
                }
            } else {
                return array('status' => 0, 'error' => "提交审核数量达到上限");
            }
            //发送通知
            $this->sendMessage($user['data']['name'], $bacteria['chinese_name'], 0);
            Db::commit();
            return array('status' => 1, 'data' => '提交成功');
        } catch (Exception $e) {
            Db::rollback();
            //            return array('status' => 0, 'error' => $e->getMessage());
            return array('status' => 0, 'error' => "数据出错");
        }
    }

    public
    function searchCategoryByBacteriaId($bacterId)
    {
        $categorylist = model('BacteriaCategory')->where(array('bacteria_id' => $bacterId))->select();
        for ($i = 0; $i < 7; $i++) {
            $category[$i] = model('Category')->where(array('id' => $categorylist[$i]['category_id']))->find();
        }
        return $category;
    }

    public
    function isVerifyMaxNum($verify_num)
    {
        $verify_max_num = model('Config')->where(array('name' => Constant::VERIFY_MAX_NUM))->value('value');
        if ($verify_num < $verify_max_num)
            return true;
        else
            return false;
    }

    public
    function getCategoryChineseName($category_id)
    {
        $categoryChineseName = model('category')->where(array('id' => $category_id))->value('name');
        return $categoryChineseName;
    }

    public
    function getCategoryEnglishName($category_id)
    {
        $categoryEnglishName = model('category')->where(array('id' => $category_id))->value('english_name');
        return $categoryEnglishName;
    }

    public function sendMessage($name, $bacteriaName, $type)
    {
        $admin = model('User')
            ->where(array('is_manager' => 1))
            ->select();
        foreach ($admin as $key => &$value) {
            if ($value['id'] != 0) {
                $message_logic = new MessageLogic();
                if ($type) {
                    $message = $name . "用户" . "提交了一条" . $bacteriaName . "的审核";
                } else {
                    $message = $name . "用户" . "修改了一条" . $bacteriaName . "的审核";
                }

                $message_logic->sendMessage($value['id'], $message);
            }
        }
    }

}